package com.example.wac.interceptor;

import com.example.wac.annotation.CurrentLimiting;
import com.example.wac.component.RedisHelper;
import com.example.wac.enums.ErrorCode;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author wuancheng
 * @description
 * @date 2023-05-31 15:29:00
 */

@Component
@Aspect
public class CurrentLimitingAspect {

    @Autowired
    private RedisHelper redisHelper;

    @Pointcut("@annotation(com.example.wac.annotation.CurrentLimiting)")
    public void pointCut(){}

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        CurrentLimiting annotation = AnnotationUtils.findAnnotation(method, CurrentLimiting.class);
        if (annotation != null) {
            String path = annotation.value();
            if (StringUtils.isNotBlank(path)) {
                boolean allow = redisHelper.isAllow(path);
                if (allow) {
                    return joinPoint.proceed();
                } else {
                    throw ErrorCode.BLOCKED_USER.getAppException();
                }
            }
        }
        return joinPoint.proceed();
    }
}
